// pages/levels/levels.js
const app = getApp();

Page({
  data: {
    levels: [],
    currentLevel: 1
  },

  onLoad() {
    this.initLevels();
    this.setData({
      currentLevel: app.globalData.currentLevel
    });
  },

  initLevels() {
    const levels = [];
    for (let i = 1; i <= 20; i++) {
      const bestScore = app.globalData.bestScores[i] || 0;
      const isUnlocked = i <= app.globalData.currentLevel;
      const stars = this.getStars(i, bestScore);
      
      levels.push({
        level: i,
        targetScore: this.getTargetScore(i),
        bestScore: bestScore,
        stars: stars,
        isUnlocked: isUnlocked,
        difficulty: this.getDifficulty(i),
        difficultyText: this.getDifficultyText(i)
      });
    }
    
    this.setData({ levels });
  },

  getTargetScore(level) {
    // 根据关卡计算目标分数
    return 1000 + (level - 1) * 200;
  },

  getStars(level, score) {
    const targetScore = this.getTargetScore(level);
    if (score >= targetScore * 1.5) return 3;
    if (score >= targetScore * 1.2) return 2;
    if (score >= targetScore) return 1;
    return 0;
  },

  getDifficulty(level) {
    if (level <= 5) return 'easy';
    if (level <= 10) return 'normal';
    if (level <= 15) return 'hard';
    return 'expert';
  },

  getDifficultyText(level) {
    if (level <= 5) return '简单';
    if (level <= 10) return '普通';
    if (level <= 15) return '困难';
    return '专家';
  },

  selectLevel(e) {
    const level = e.currentTarget.dataset.level;
    const isUnlocked = e.currentTarget.dataset.unlocked;
    
    if (!isUnlocked) {
      wx.showToast({
        title: '请先通过前面的关卡',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/game/game?level=${level}`
    });
  },

  goBack() {
    wx.navigateBack();
  }
})